const fs = require("fs")
const http = require("http")
const urlLib = require("url")
const querystring = require("querystring")

var users = {}      //{"blue": "123456", "zhangsan": "123456", "lisi": "321321"}

http.createServer(function(req,res){
    //解析数据
    var str = ''
    req.on('data',(data)=>{
        str += data
    })
    req.on('end',()=>{
        var obj = urlLib.parse(req.url,true)
        
        const url = obj.pathname;
        const GET = obj.query;
        const POST = querystring.parse(str);

        //区别访问接口(自定义)，文件
        if(url=='/user'){   //接口     localhost:8080/user?act=login&user=bule&pass=123456
            switch(GET.act){
                case 'reg':
                    //1.检查用户名是否注册
                    if(users[GET.user]){
                        res.write('{"ok":false,"msg":"用户已注册"}')
                    }
                    else{
                    //2.插入数据
                        users[GET.user]=GET.pass
                        res.write('{"ok":true,"msg":"注册成功"}')
                    }
                    break;
                case 'login':
                    //1.检查用户名是否存在
                    if(users[GET.user]==null){
                        res.write('{"ok":false,"msg":"用户不存在"}')
                    }else if(users[GET.user]!=GET.pass){
                    //2.检查密码是否正确
                        res.write('{"ok":false,"msg":"用户或密码错误"}')
                    }else{
                        res.write('{"ok":true,"msg":"登录成功"}')
                    }
                    break;
                default:
                    res.write('{"ok":false,"msg":"未知的act"}')
            }
            res.end()
        }else{              //文件      localhost:8080/1.html
            var file_name = './www' + url;
            fs.readFile(file_name,(err ,data)=>{
                if(err){
                    res.write('404')
                }else{
                    res.write(data)
                }
                res.end()
            })  
        }
    })
}).listen(8080);